//
//  LcbDevice.m
//  lcb
//
//  Created by lcb on 16/5/23.
//  Copyright © 2016年 lcb. All rights reserved.
//

#import "LcbDevice.h"
#import <sys/utsname.h>
#import "zlib.h"
#import <execinfo.h>
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonCrypto.h>
#import <netdb.h>
#import "LcbReachability.h"
#import "KeychainItemWrapper.h"


@import CoreTelephony;
@import SystemConfiguration;

static NSString *MD5(NSString *originString) {
    const char* callStackSymbolsStr = [originString UTF8String];
    unsigned char result[16];
    CC_MD5( callStackSymbolsStr, (int)strlen(callStackSymbolsStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


@implementation LcbDevice
LcbSingletonM(LcbDevice)
@synthesize accesstoken=_accesstoken;
@synthesize domain=_domain;

+ (NSString *)getUDID {
    KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Account Number" accessGroup:nil];
    //    [wrapper resetKeychainItem];//清除数据
    
    //从keychain里取出UUID
    NSString *uUIDString = [wrapper objectForKey:(__bridge id)kSecAttrAccount];
    
    NSString *identify;
    if (uUIDString && uUIDString.length !=0) {
        identify = uUIDString;
    } else {
        //保存数据
        NSString *uuid = [[UIDevice currentDevice].identifierForVendor UUIDString];
        [wrapper setObject:@"UUID_YIBAN" forKey:(__bridge id)kSecAttrService];
        //判断字典中object是否为空
        if (uuid){
            [wrapper setObject:uuid forKey:(__bridge id)kSecAttrAccount];
        }
        identify = uuid;
    }
    wrapper=nil;
    return identify;
}
+(NSString*)convertIntervalStringFromDate:(NSDate*)date
{
    NSTimeInterval interval = [date timeIntervalSince1970];
    long long int dateInterval = (long long int)interval;
    NSString *str = [NSString stringWithFormat:@"%lld",dateInterval];
    return str;
}

+(NSDate*)convertDateFromIntervalString:(NSString*)string
{
    if (![string isKindOfClass:[NSString class]]) {
        return nil;
    }
    
    NSTimeInterval interval = [string doubleValue];
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:interval];
    return date;
}

+ (NSString *)getSigTime {
    NSUserDefaults *userDict = [NSUserDefaults standardUserDefaults];
    NSString *username = [userDict stringForKey:@"username"];
    NSString *timeString;
    
    if ([userDict stringForKey:@"sigTimeString"]) {
        timeString = [userDict stringForKey:@"sigTimeString"];
    } else {
        timeString = [self convertIntervalStringFromDate:[NSDate date]];
        [userDict setValue:timeString forKey:@"sigTimeString"];
        [userDict synchronize];
    }
    NSString *sigString = [NSString stringWithFormat:@"%@%@",username,timeString];
    
    const char *cStr = [sigString UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, strlen(cStr), result );
    NSString *resStr = [NSString stringWithFormat:
                        @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                        result[0], result[1], result[2], result[3],
                        result[4], result[5], result[6], result[7],
                        result[8], result[9], result[10], result[11],
                        result[12], result[13], result[14], result[15]
                        ];
    resStr = [resStr substringWithRange:NSMakeRange(8, 16)];
    return resStr;
}
+ (NSString*) getModel{
    
    struct utsname u;
    uname(&u);
    return [NSString stringWithCString: u.machine encoding: NSUTF8StringEncoding];
}
+ (NSString*) getCarrier{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    NSString* carrier = [info.subscriberCellularProvider carrierName];
    return carrier ? carrier : @"";
}

+ (NSString*) getResolution{
    CGSize size = [UIScreen instancesRespondToSelector:@selector(currentMode)] ?
    [[UIScreen mainScreen] currentMode].size : [UIScreen mainScreen].bounds.size;
    return [NSString stringWithFormat:@"%.0fx%.0f", size.width, size.height];
}

+ (NSString*) getNetwork{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    zeroAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
    SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault,
                                                                          (const struct sockaddr*)&zeroAddress);
    SCNetworkReachabilityFlags flags = 0;
    SCNetworkReachabilityGetFlags(ref, &flags);
    CFRelease(ref);
    
    if (flags & kSCNetworkReachabilityFlagsTransientConnection) return @"wifi";
    if (flags & kSCNetworkReachabilityFlagsConnectionRequired) return @"wifi";
    if (flags & kSCNetworkReachabilityFlagsIsDirect) return @"wifi";
    if (flags & kSCNetworkReachabilityFlagsIsWWAN) return @"cellnetwork";
    return @"unknow";
}

+ (NSString*) getAppVersion{
    return [[[NSBundle mainBundle] infoDictionary]
            objectForKey:@"CFBundleShortVersionString"];
}

+ (NSString*) getOsVersion{
    return [NSString stringWithFormat:@"%@",[[UIDevice currentDevice] systemVersion]];
}
//判断屏幕  1，iphone6plus；2, iphone6, 3, iphone5, 0，iphone4，4s，touch
+ (NSInteger)boundSizeType
{
    CGSize mainSize = [UIScreen mainScreen].bounds.size;
    
    if (mainSize.height > 667)
    {
        return 1;
    }else if (mainSize.height > 568){
        return 2;
    }else if (mainSize.height > 480){
        return 3;
    }else{
        return 0;
    }
}
+ (bool) isJailbroken{
    static bool isChecked = NO;
    static bool isJailbroken = NO;
    if(!isChecked){
        if ([[NSFileManager defaultManager] fileExistsAtPath:@"/Applications/Cydia.app"]) {
            isJailbroken = YES;
        }else if([[NSFileManager defaultManager] fileExistsAtPath:@"/private/var/lib/apt"]){
            isJailbroken = YES;
        }
    }
    return isJailbroken;
}


+ (NSDictionary *)deviceInfoDict {
    UIDevice * device = [UIDevice currentDevice];
    NSString *uuid =[self getUDID];
    if (uuid==nil) {
        uuid=@"";
    }
    NSString *carrier =[self getCarrier];
    if (carrier==nil) {
        carrier=@"";
    }
    NSString *network =[self getNetwork];
    if (network==nil) {
        network=@"";
    }
    NSString *resolution =[self getResolution];
    if (resolution==nil) {
        resolution=@"";
    }
    id jail =@([self isJailbroken]);
    if (jail==nil) {
        jail=@"";
    }
    UIScreen * screenDevice = [UIScreen mainScreen];
    NSDictionary * dicApp = [[NSBundle mainBundle] infoDictionary];
    return  @{@"device_name":[device name],
              @"device_unique_id":uuid,
              @"system_name":[device systemName],
              @"system_version": [device systemVersion],
              @"device_model":[device model],
              @"device_local_model":[device localizedModel],
              @"device_locale":[[NSLocale currentLocale] localeIdentifier],
              @"device_root":[NSNumber numberWithInt:([self isJailbroken] ? 1 : 0) ],
              @"screen_width":[NSNumber numberWithFloat:screenDevice.bounds.size.width],
              @"screen_height":[NSNumber numberWithFloat:screenDevice.bounds.size.height] ,
              @"app_name":[dicApp objectForKey:@"CFBundleDisplayName"],
              @"app_version": [dicApp objectForKey:@"CFBundleShortVersionString"],
              @"app_build":[dicApp objectForKey:@"CFBundleVersion"],
              @"network":network,
              @"carrier":carrier,
              @"resolution":resolution};
   
}


+ (NSString *)deviceInfoDesctirtion {
    NSError *error;
    NSData *data = [NSJSONSerialization dataWithJSONObject:[self deviceInfoDict] options:NSJSONWritingPrettyPrinted error:&error];
    NSLog(@"this is desc :%@",error ? [error localizedDescription] : [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    return error ? [error localizedDescription] : [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//网络连接方式
+(NSString *)networkType{
    
    //1-3G,2-2G,3-WiFi
    LcbReachability* curReach;
    NSString *ret=@"2g";
    
    if (!curReach)
    {
        curReach = [LcbReachability reachabilityForInternetConnection];
    }
    
    LcbNetworkStatus netStatus = [curReach currentReachabilityStatus];
    
    switch (netStatus)
    {
        case LcbNotReachable:
        {
            ret=@"-1";
            break;
        }
            
        case LcbReachableViaWWAN:
        {
            ret=@"2g";
            break;
        }
        case LcbReachableViaWiFi:
        {
            ret=@"wifi";
            break;
        }
    }
    
    return ret;
}
@end
